<?php

namespace api\controllers;

use common\helpers\ArrayHelper;
use services\common\CommonService;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use common\helpers\CommonHelper;
use common\models\base\Profession;
use common\models\member\Attr;
use common\models\member\Member;

/**
 * 需要授权登录访问基类
 *
 * Class OnAuthController
 * @package api\controllers
 * @property yii\db\ActiveRecord|yii\base\Model $modelClass
 */
class OnAuthController extends ActiveController
{
    protected $projectId = 0;

    // 请求参数
    public $post;
    public $get;

    /**
     * @return array
     */
    public function actions()
    {
        $actions = parent::actions();

        // 注销系统自带的实现方法
        unset($actions['index'], $actions['update'], $actions['create'], $actions['view'], $actions['delete']);

        // 自定义数据indexDataProvider覆盖IndexAction中的prepareDataProvider()方法
        // $actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
        return $actions;
    }

    /**
     * 验证更新是否本人
     *
     * @param $action
     * @return bool
     * @throws NotFoundHttpException
     * @throws \yii\web\BadRequestHttpException
     * @throws \yii\web\ForbiddenHttpException
     * @throws HttpException
     */
    public function beforeAction($action)
    {
        // 过滤参数空格
        Yii::$app->request->setBodyParams(ArrayHelper::trim(Yii::$app->request->post()));
        Yii::$app->request->setQueryParams(ArrayHelper::trim(Yii::$app->request->get()));

        // 项目ID
        $this->projectId = $projectId = Yii::$app->request->headers->get('ProjectId', 0);
        if (!$this->projectId) {
            $this->projectId = Yii::$app->request->get('project_id', 0);
        }
        Yii::$app->params['project_id'] = $this->projectId;
        // 是否客服、是否医助
        Yii::$app->params['is_customer'] = Yii::$app->params['is_assistant'] = 0;
        // 是否为负责人
        Yii::$app->params['is_department_leader'] = 0;
        // 所属部门
        Yii::$app->params['department_id'] = 0;
        // 所属岗位
        Yii::$app->params['profession_id'] = 0;

        // 请求参数
        $this->post = Yii::$app->request->post();
        $this->get = Yii::$app->request->get();

        // 身份验证
        $return = parent::beforeAction($action);

        // 权限验证
        if (!Yii::$app->user->isGuest) {
            // 方法名
            $actionName = $action->id;

            if (!in_array($actionName, $this->optionalLimit)) {
                $route = $action->getUniqueId();
                // $route = $this->module->module->requestedRoute;
                $member = Yii::$app->user->identity->member;
                
                if(Yii::$app->request->isPost && $route != 'v1/infusion/queue/create') {
                    $url = CommonHelper::getUrl();
                    $key = 'baiyou-'.$projectId.'-'.$member->id.'-'.$url;
                    $lock = CommonService::acquire_global_lock($key);
                    if (empty($lock)) {
                        throw new HttpException(422, '请勿重复提交');
                    }
                }

                if (!Yii::$app->services->member->checkAccess($member, $route, $projectId)) {
                    throw new HttpException(422, '权限不足.');
                }
            }

            $attr = Yii::$app->services->attr->findInfo([
                'member_id' => Yii::$app->user->identity->member_id,
                'project_id' => Yii::$app->params['project_id'],
            ]);
            if ($attr) {
                if ($attr->profession_id == Profession::ID_MEDICAL) {// 医助
                    Yii::$app->params['is_assistant'] = 1;
                } elseif ($attr->profession_id == Profession::ID_CUSTOMER) {// 客服
                    Yii::$app->params['is_customer'] = 1;
                }

                Yii::$app->params['is_department_leader'] = $attr->is_department_leader;
                Yii::$app->params['department_id'] = $attr->department_id;
                Yii::$app->params['profession_id'] = $attr->profession_id;
            }

            if (Yii::$app->user->identity->member->is_super == Member::IS_SUPER_YES) {
                Yii::$app->params['is_department_leader'] = Attr::IS_DEPARTMENT_LEADER_PROJECT;
            }
        }

        return $return;
    }

    /**
     * 首页
     *
     * @return ActiveDataProvider
     */
    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->where(['status' => 1])
                ->orderBy('id desc')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }

    /**
     * 创建
     *
     * @return mixed|\yii\db\ActiveRecord
     */
    public function actionCreate()
    {
        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass();
        $model->attributes = Yii::$app->request->post();
        // $model->member_id = Yii::$app->user->identity->member_id;
        if (!$model->save()) {
            return CommonHelper::api(422, $this->getError($model));
        }

        return $model;
    }

    /**
     * 更新
     *
     * @param $id
     * @return mixed|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $model->attributes = Yii::$app->request->post();
        if (!$model->save()) {
            return CommonHelper::api(422, $this->getError($model));
        }

        return $model;
    }

    /**
     * 删除
     *
     * @param $id
     * @return bool
     * @throws NotFoundHttpException
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->status = -1;
        return $model->save();
    }

    /**
     * 单个显示
     *
     * @param $id
     * @return \yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        return $this->findModel($id);
    }

    /**
     * @param $id
     * @return \yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || !($model = $this->modelClass::find()->where([
                'id' => $id,
                'status' => [0, 1]
            ])->one())) {
            throw new NotFoundHttpException('请求的数据不存在');
        }

        return $model;
    }

    /**
     * @Notes: 名称重复判断
     *
     * @Interface actionHaveModel
     * @param $name
     * @param int $id
     * @return bool|mixed
     * @throws NotFoundHttpException
     * @author: wanfengling
     */
    public function actionHaveModel($name, $id = 0)
    {
        if (empty($name)) {
            throw new NotFoundHttpException('请求的数据不存在');
        }
        // 新增
        $where = ['>', 'id', 0];
        // 编辑
        if ($id) {
            $where = ['!=', 'id', $id];
        }

        if ($this->modelClass::find()
            ->where(['name' => $name, 'status' => [0, 1]])
            ->andWhere($where)
            ->one()) {
            return CommonHelper::api(422, '该名称已存在');
        }
        return true;
    }
}
